package com.example.auction.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.*;
import android.widget.*;
import com.example.auction.R;
import com.example.auction.activity.ItemDetailsViewActivity;
import com.example.auction.aliplay.AliPlayOfSandboxActivity;
import com.example.auction.bean.Item;
import com.example.auction.sqlite.Sqlite;
import com.example.auction.util.MyFinishedScrollView;
import com.example.auction.util.MyUtil;
import com.example.auction.util.UserDialog;

import java.util.List;

//性能优化，把频繁fvbi优化
public class FinishedItemListAdapter extends BaseAdapter {


    private List<Item> itemList;
    private final LayoutInflater layoutInflater;
    private Context context;

    private View nowView = null;
    private View preView = null;
    private float downx = 0;
    private float upx = 0;
//    private int pos;

    private Integer user_id;
    private String finishstate;
    private Sqlite sqlite;
    private String ownerName;
    private Bitmap imagebm;

    //构造方法
    public FinishedItemListAdapter(Context context, List<Item> itemList, Integer user_id, String finished) {
        this.context = context;
        this.itemList = itemList;
        //获取用户id
        this.user_id = user_id;
        this.finishstate = finished;

        sqlite = new Sqlite(this.context);

        layoutInflater = LayoutInflater.from(context);
    }


    //返回数据源列表的条数
    @Override
    public int getCount() {
        return itemList.size();
    }

    //返回选中的item子项
    @Override
    public Object getItem(int position) {
        return itemList.get(position);
    }

    //返回选中的item子项的位置（第几条）
    @Override
    public long getItemId(int position) {
        return position;
    }

    //显示数据的主要方法
    @SuppressLint({"ClickableViewAccessibility", "Range"})
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

//        final String info = itemList.get(position).get("info").toString();

        //viewHolder相当于暂时存储数据的容器，减少数据加载时间
        ViewHolder viewHolder = new ViewHolder();

        //优化版，把频繁fvbi优化
        if (convertView == null) {
            //创建视图控件，绑定item子项的布局文件
            convertView = layoutInflater.inflate(R.layout.list_adapter_finished_item, parent, false);

            //绑定数据布局位置
            //viewHolder相当于暂时存储数据的容器
            viewHolder.viewScrollview = convertView.findViewById(R.id.view_scrollview);
            viewHolder.llLeft = convertView.findViewById(R.id.ll_left);

            //等待收货标签
            viewHolder.tvFinishTips = convertView.findViewById(R.id.tv_finish_tips);

            viewHolder.ivFinishedItemListImg = convertView.findViewById(R.id.iv_finished_item_list_img);
            viewHolder.tvFinishedItemListName = convertView.findViewById(R.id.tv_finished_item_list_name);
            viewHolder.tvFinishedItemListDes = convertView.findViewById(R.id.tv_finished_item_list_des);
            viewHolder.tvFinishedItemListMaxPrice = convertView.findViewById(R.id.tv_finished_item_list_max_price);
            viewHolder.tvFinishedItemListOwner = convertView.findViewById(R.id.tv_finished_item_list_owner);
            viewHolder.tvFinishedItemListEndtime = convertView.findViewById(R.id.tv_finished_item_list_endtime);

            viewHolder.ibtnPay = convertView.findViewById(R.id.ibtn_pay);
            viewHolder.ibtnDeleteFinishedItem = convertView.findViewById(R.id.ibtn_delete_finished_item);

            //获取系统服务，Context.WINDOW_SERVICE在获取窗口服务
            WindowManager wm = (WindowManager) context
                    .getSystemService(Context.WINDOW_SERVICE);
            //获取原宽度
            viewHolder.llLeft.getLayoutParams().width = wm.getDefaultDisplay().getWidth();

            //将fvbi的值都保存
            convertView.setTag(viewHolder);
        } else {
            //取出数据，不用多次fvbi，减少数据加载时间
            viewHolder = (ViewHolder) convertView.getTag();
        }

        final View finalView = convertView;

        //滑动菜单
        viewHolder.viewScrollview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //操作：按下、移动、抬起
                switch (event.getAction()) {
                    //按下
                    case MotionEvent.ACTION_DOWN:
                        //获取按下位置
                        downx = event.getX();
                        break;
                    //移动
                    case MotionEvent.ACTION_MOVE:
                        break;
                    //抬起
                    case MotionEvent.ACTION_UP:
                        //获取抬起位置
                        upx = event.getX();
                        float modify = downx - upx;
                        if (modify == 0) {
                            preView = nowView;
                            nowView = v;
                            autoHide1();
//                            TextView t = v.findViewById(R.id.list_title);
//                            Log.i("Furrain", (String) t.getText());
                            return false;
                        } else {
                            if (nowView == null) {
                                preView = null;
                            } else {
                                preView = nowView;
                            }
                            if (nowView == v) {
                                return false;
                            }
                            nowView = v;
                            autoHide();
                            return false;
                        }
                }
                return false;
            }
        });

        //获取位置对应的对象
        Item item = itemList.get(position);
        Integer item_id = itemList.get(position).getItemId();

        imagebm = BitmapFactory.decodeByteArray(item.getImage(), 0, item.getImage().length);
        ownerName = MyUtil.getUserNameByID(context, item.getOwnerId());
        Integer bid_finish = 0;

        Integer winner_id = itemList.get(position).getWinnerId();
        if (winner_id != 0){
            Cursor cursor = sqlite.selectBid(item_id, winner_id);
            if (cursor != null && cursor.moveToFirst()) {
                bid_finish = cursor.getInt(cursor.getColumnIndex("bid_finish"));
            }
        }else{
            //若卖家结束拍卖时无人出价，则bid_finish为-1
            bid_finish = -1;
        }

        if (bid_finish == 0) {
            viewHolder.tvFinishTips.setText("等待付款");
            viewHolder.tvFinishTips.setBackgroundResource(R.color.state_yellow);
        }
        if (bid_finish == 1) {
            viewHolder.tvFinishTips.setText("交易完成");
            viewHolder.tvFinishTips.setBackgroundResource(R.color.state_green);
        }
        if (bid_finish == -1){
            viewHolder.tvFinishTips.setText("无人出价");
            viewHolder.tvFinishTips.setBackgroundResource(R.color.state_gray);
        }

        if (finishstate.equals("我卖出的")) {
            viewHolder.ibtnPay.setVisibility(View.GONE);
        } else if (finishstate.equals("我买到的")) {
            if (bid_finish == 0){
                viewHolder.ibtnPay.setVisibility(View.VISIBLE);
            }
            else if (bid_finish == 1){
                //付款后按钮消失
                viewHolder.ibtnPay.setVisibility(View.GONE);
            }
        }

        viewHolder.ivFinishedItemListImg.setImageBitmap(imagebm);
        viewHolder.tvFinishedItemListName.setText(item.getItemName());
        viewHolder.tvFinishedItemListDes.setText(item.getItemDesc());
        viewHolder.tvFinishedItemListMaxPrice.setText(item.getMaxPrice());
        viewHolder.tvFinishedItemListOwner.setText(ownerName);
        viewHolder.tvFinishedItemListEndtime.setText(item.getEndtime());

        //子项点击监听
        viewHolder.llLeft.setOnClickListener(new MyAdapterListener(position));
        //左滑菜单功能监听
        viewHolder.ibtnPay.setOnClickListener(new leftSlideBtn(position));
        viewHolder.ibtnDeleteFinishedItem.setOnClickListener(new leftSlideBtn(position));

        return convertView;
    }

    //优化版，把频繁fvbi优化
    class ViewHolder {
        //保存控件数据，防止多次fvbi
        MyFinishedScrollView viewScrollview;
        LinearLayout llLeft;
        TextView tvFinishTips;
        ImageView ivFinishedItemListImg;
        TextView tvFinishedItemListName;
        TextView tvFinishedItemListDes;
        TextView tvFinishedItemListMaxPrice;
        TextView tvFinishedItemListOwner;
        TextView tvFinishedItemListEndtime;

        ImageButton ibtnPay;
        ImageButton ibtnDeleteFinishedItem;
    }


    //！！！十点搞到了六点，防止item点击错乱的方法
    private class MyAdapterListener implements View.OnClickListener {
        private int position;

        public MyAdapterListener(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            Integer item_id = itemList.get(position).getItemId();
            Toast.makeText(context, "您选择的是：" + item_id, Toast.LENGTH_SHORT).show();

            //将用户id以及点击的拍卖品名传给拍卖品竞价页
            Intent intent = new Intent();
            intent.putExtra("user_id", user_id);
            intent.putExtra("item_id", item_id.toString());
            //传递从哪个页面跳转过去的信标
            intent.putExtra("from", finishstate);
            intent.setClass(context, ItemDetailsViewActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(intent);
        }
    }

    @SuppressLint("Range")
    //左滑菜单
    private class leftSlideBtn implements View.OnClickListener {
        private int position;
        private UserDialog finishDialog;
        private Integer item_id;
        private Integer winner_id;
        private Cursor cursor;


        private String max_price;
        private String item_name;

        private Integer bid_finish;


        public leftSlideBtn(int position) {
            this.position = position;
            item_id = itemList.get(position).getItemId();
            item_name = itemList.get(position).getItemName();
            winner_id = itemList.get(position).getWinnerId();

            if (winner_id != 0) {
                cursor = sqlite.selectBid(item_id, winner_id);
                if (cursor != null && cursor.moveToFirst()) {
                    bid_finish = cursor.getInt(cursor.getColumnIndex("bid_finish"));
                }
                max_price = itemList.get(position).getMaxPrice();
            } else {
                //若卖家结束拍卖时无人出价，则bid_finish为-1
                bid_finish = -1;
            }
        }

        @SuppressLint("NonConstantResourceId")
        @Override
        public void onClick(View v) {

            v.scrollTo(0, 0);
            notifyDataSetChanged();
            autoHide1();

            switch (v.getId()) {
                //确认收货
                case R.id.ibtn_pay:
                    finishDialog = new UserDialog(context, new payDialog());
                    finishItemState("pay");
                    break;

                case R.id.ibtn_delete_finished_item:
//                    itemList.remove(pos);
//                    Toast.makeText(context, "点击了删除按钮", Toast.LENGTH_SHORT).show();
                    finishDialog = new UserDialog(context, new deleteDialog());
                    finishItemState("delete");
                    break;
            }
        }

        //结束拍卖弹出框标题和内容
        private void finishItemState(String clickFrom) {
            //确认收货
            if (clickFrom.equals("pay")) {
                if (finishstate.equals("我买到的")) {
//                    Toast.makeText(context,"" + winner_id, Toast.LENGTH_SHORT).show();
                    if (bid_finish == 0) {
                        finishDialog.setTitle("支付宝支付").show();
                        finishDialog.setContent("即将跳转到支付页面").show();
                    } else if (bid_finish == 1) {
                        finishDialog.setTitle("支付宝支付").show();
                        finishDialog.setContent("你已支付过该订单").show();
                    }
                }
            }
            //删除物品
            else {
                finishDialog.setTitle("删除物品").show();
                if (finishstate.equals("我买到的")) {
                    if (bid_finish == 0) {
                        finishDialog.setContent("交易完成后才可以删除！").show();
                    } else if (bid_finish == 1) {
                        finishDialog.setContent("请确认删除，删除后不可恢复！").show();
                    }
                } else if (finishstate.equals("我卖出的")) {
                    if (bid_finish == 0) {
                        finishDialog.setContent("交易完成后才可以删除！").show();
                    } else if (bid_finish == 1 || bid_finish == -1) {
                        finishDialog.setContent("请确认删除，删除后不可恢复！").show();
                    }
                }
            }

        }

        //重确认收货弹出框确认按钮
        private class payDialog implements UserDialog.OnCloseListener {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (bid_finish == 0) {
                    Intent intent = new Intent(context, AliPlayOfSandboxActivity.class);
                    intent.putExtra("item_id",item_id);
                    intent.putExtra("winner_id",winner_id);
                    intent.putExtra("max_price",max_price);
                    intent.putExtra("owner_name",ownerName);
                    intent.putExtra("item_name",item_name);
                    intent.putExtra("imagebm",imagebm);

                    ((Activity)context).startActivityForResult(intent,0);
                    /*//更新竞价表bid_finish
                    long i = sqlite.updateBid(
                            item_id, winner_id, "bid_finish", Integer.valueOf(1).toString());
                    if (i > 0) {
                        //刷新界面
                        notifyDataSetChanged();
                        Toast.makeText(context, "交易成功！", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, "操作失败", Toast.LENGTH_SHORT).show();
                    }*/
                } else if (bid_finish == 1) {
                    dialog.dismiss();
                }
                dialog.dismiss();
            }
        }

        //删除物品弹框确认监听
        private class deleteDialog implements UserDialog.OnCloseListener {
            @Override
            public void onClick(android.app.Dialog dialog, boolean confirm) {
                if (finishstate.equals("我买到的")) {
                    if (bid_finish == 0) {
                        dialog.dismiss();
                    } else if (bid_finish == 1) {
                        long i = sqlite.updateItem(
                                item_id, "winner_visible", Integer.valueOf(0).toString());
                        if (i > 0) {
                            //移除子项
                            itemList.remove(position);
                            //刷新界面
                            notifyDataSetChanged();
                            Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(context, "删除失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                    dialog.dismiss();
                } else if (finishstate.equals("我卖出的")) {
                    if (bid_finish == 0) {
                        dialog.dismiss();
                    } else if (bid_finish == 1 || bid_finish == -1) {
                        long i = sqlite.updateItem(
                                item_id, "owner_visible", Integer.valueOf(0).toString());
                        if (i > 0) {
                            //移除子项
                            itemList.remove(position);
                            //刷新界面
                            notifyDataSetChanged();
                            Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(context, "删除失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                    dialog.dismiss();
                }
            }
        }
    }

    //删除之后回到原位
    private void autoHide() {
        if (preView != null) {
            MyFinishedScrollView v = (MyFinishedScrollView) preView;
            v.smoothScrollTo(0, 0);
        }
    }

    private void autoHide1() {
        if (preView != null) {
            MyFinishedScrollView view = (MyFinishedScrollView) preView;
            view.smoothScrollTo(0, 0);
        }
        if (nowView != null) {
            MyFinishedScrollView view = (MyFinishedScrollView) nowView;
            view.smoothScrollTo(0, 0);
        }
    }
}
